package com.empoweragile.web.filter_bullet;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class PassivationListener implements HttpSessionListener {

	private static final String minimumSessionsParameter = "filter-bullet:min-sessions";
	private static final String minimumIdleTimeParameter = "filter-bullet:min-idle-time";

	private long minimumSessions;
	private long minimumIdleTime;
	private long sessionCount;
	
	private long oldestSessionCreationTime;
	private String oldestSessionId;
	HttpSessionContext context;

	@Override
	public void sessionCreated(HttpSessionEvent event) {

		readParameters(event);
		context = (HttpSessionContext) event.getSession().getServletContext();
		
		countSessionsAndObtainOldestSessionInfo();
		
		if( ! sessionCountTrasholdReached()){
			return;
		}
		
		if( ! idleSessionExist()){
			return;
		}
		
		passivateOldestSession();
		
	}	

	private void passivateOldestSession() {
		HttpSession oldestSession = context.getSession(oldestSessionId);
		Map sessionAttributes = new HashMap();
		
	}

	private boolean idleSessionExist() {
		if(System.currentTimeMillis() - oldestSessionCreationTime > minimumIdleTime * 1000){
			return true;
		}			
		return false;
	}

	private boolean sessionCountTrasholdReached() {
		return sessionCount > minimumSessions;
	}

	private void countSessionsAndObtainOldestSessionInfo() {
		Enumeration<String> ids = context.getIds();
		while(ids.hasMoreElements()){
			sessionCount++;
			HttpSession session = context.getSession(ids.nextElement());
			if(oldestSessionCreationTime<session.getCreationTime()){
				oldestSessionCreationTime = session.getCreationTime();
				oldestSessionId = session.getId();
			}
		}
	}

	private void readParameters(HttpSessionEvent event) {		
		
		minimumSessions = initialParameterToInteger(event.getSession()
				.getServletContext().getInitParameter(
						minimumSessionsParameter));
		
		minimumIdleTime = initialParameterToInteger(event.getSession()
				.getServletContext().getInitParameter(
						minimumIdleTimeParameter));

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub

	}

	private long initialParameterToInteger(String initialParameter) {
		return initialParameter.length() > 0 ? new Long(initialParameter) : 0;
	}

}
